import express from "express";
import multer from "multer";
import fs from "fs";
import path, { dirname, parse, join } from "path";
import { fileURLToPath } from "url";
import mammoth from "mammoth";
import cors from "cors";

const app = express();
const port = 3000;

// 获取 __dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// 静态资源
app.use(express.static("public"));
app.use(cors());

// 上传目录
const upload = multer({ dest: "uploads/" });

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  next();
});

app.post("/upload", upload.single("file"), async (req, res) => {
  try {
    const buffer = fs.readFileSync(req.file.path);

    // 使用 convertImage 自定义图片处理：返回 <img src="">
    const result = await mammoth.convertToHtml({
      buffer,
      convertImage: mammoth.images.imgElement(() => {
        return { src: "" }; // src 空
      }),
    });

    const bodyContent = result.value; // 只有内容

    // 拼接完整 HTML 页面
    const htmlContent = `<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>${parse(req.file.originalname).name}</title>
  </head>
  <body>
    ${bodyContent}
  </body>
</html>`;

    // 自动生成 HTML 文件名
    const originalName = parse(req.file.originalname).name;
    const htmlFileName = `${originalName}_${Date.now()}.html`;
    const htmlFilePath = join(__dirname, "uploads", htmlFileName);

    // 写入文件
    fs.writeFileSync(htmlFilePath, htmlContent, "utf-8");

    res.json({
      html: htmlContent,
      savedFile: htmlFileName,
      path: `/uploads/${htmlFileName}`,
    });
  } catch (err) {
    res.status(500).send("转换失败: " + err.message);
  } finally {
    if (req.file && fs.existsSync(req.file.path)) fs.unlinkSync(req.file.path);
  }
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
